//index.js
//获取应用实例
//import { token } from '../../env';
import { fromNow } from '../../utils/util';
import { apiUrl } from '../../config';
import { filter, find, indexOf } from '../../utils/lodash';
const app = getApp();
let token = null;
Page({
  data: {
    feed: null,
    loading: false,
    threadId: null,
    success: true,
    metaType: 'comment',
    filterUid: null,
    commentList: [],
    commentPage: 1,
    commentMore: false,
    likeList: [],
    likePage: 1,
    likeMore: false,
    hasMore: true,
    getting: false,
    getSuccess: true,
    user: null
  },
  onShow(e) {
    console.log('onShow');
    try {
      // 检查返回到首页时是否需改变数据
      var value = wx.getStorageSync('index-change');
      switch (value) {
        case 'comment': {
          wx.removeStorageSync('index-change');
          wx.removeStorageSync('comment');
          const {feed} = this.data;
          if (!!feed) {
            feed.replies++;
            this.setData({
              feed
            });
          }
          this.switchType('comment')
          break;
        }
        default: ;
      }
    } catch (e) {
      console.log(e);
    }
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          windowHeight: res.windowHeight
        })
      }
    })
  },
  previewPics(e) {
    const all = e.currentTarget.dataset.all;
    const index = e.currentTarget.dataset.current;
    console.log(index);
    wx.previewImage({
      current: all[index].url, // 当前显示图片的http链接
      urls: all.map(item => item.url) // 需要预览的图片http链接列表
    });
  },
  onLoad(options) {
    console.log(options);
    console.log(options.threadId);
    token = app.globalData.token;
    this.setData({ threadId: options.threadId || '' });
    try {
      const feed = wx.getStorageSync('feed');
      const user = wx.getStorageSync('alluser');
      if (feed && feed.thread_id == options.threadId) {
        this.setData({ feed, success: true, user });
        this.switchType('comment')
        console.log(1);
      } else {
        this.getFeed();
        this.setData({ user });
      }
    } catch (e) {
      console.log(e);
    }
    wx.showShareMenu({
      withShareTicket: true
    });
  },
  getFeed() {
    this.setData({ loading: true });
    wx.request({
      url: apiUrl + '/post/' + this.data.threadId, //仅为示例，并非真实的接口地址
      header: {
        Authorization: token
      },
      success: (res) => {
        console.log(res);
        switch (Number(res.data.code)) {
          case 1: {
            const afterFeed = res.data.data;
            afterFeed.fromNow = fromNow(afterFeed.dateline);
            afterFeed.message.replace(/<br>/g, '\n');
            this.setData({
              feed: afterFeed,
              success: true,
              loading: false
            });
            this.switchType('comment');
            break;
          }
          default: {
            wx.showModal({
              content: '加载失败',
              confirmText: '知道了',
              showCancel: false
            });
            this.setData({
              success: false,
              loading: false
            });
            break;
          }
        }
      },
      fail: () => {
        wx.showModal({
          content: '加载失败',
          confirmText: '知道了',
          showCancel: false
        });
        this.setData({
          success: false,
          loading: false
        });
      }
    })
  },
  feedAcitonSheet() {
    const { feed } = this.data;
    const { thread_id } = feed;
    let itemList = this.feedAcitonSheetList();
    wx.showActionSheet({
      itemList,
      success: (res) => {
        const index = res.tapIndex;
        console.log(typeof index);
        if (typeof index == 'number') {
          switch (itemList[index]) {
            case '删除': {
              this.postDelete(thread_id);
              break;
            }
            case '置顶': ;
            case '取消置顶': {
              this.postTop(thread_id);
              break;
            }
            default: ;
          }
        }
        console.log(res)
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  feedAcitonSheetList() {
    const menus = [];
    const { feed, user } = this.data;
    if (!!!feed) {
      return menus;
    }
    console.log(menus);
    console.log(user);
    if (!!user.member_info.is_admin) {
      menus.push('删除');
      if (!!Number(feed.user_behavior.is_top)) {
        menus.push('取消置顶');
      } else {
        menus.push('置顶');
      }
    }
    if (Number(user.user_id) === Number(feed.author_id) || !!user.member_info.is_admin) {
      menus.push('删除');
    } else {
      menus.push('');
    }
    return menus;
  },
  postDelete(thread_id) {
    wx.request({
      url: apiUrl + '/post/' + thread_id, //仅为示例，并非真实的接口地址
      method: 'DELETE',
      header: {
        Authorization: token
      },
      success: (res) => {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          setTimeout(function () {
            wx.hideToast();
            try {
              wx.setStorageSync('index-change', 'delete');
              wx.setStorageSync('thread_id', thread_id);
              wx.navigateBack({ delta: 1 })
            } catch (e) {
              console.log(e)
            }
          }, 2000);
        } else {
          wx.showModal({
            title: '失败',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  postTop(thread_id) {
    const { feed } = this.data;
    const type = feed.user_behavior.is_top;
    wx.request({
      url: apiUrl + '/post-stick', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        type,
        thread_id
      },
      header: {
        Authorization: token
      },
      success: (res) => {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          setTimeout(function () {
            wx.hideToast()
          }, 2000);
          if (type == 0) {
            feed.user_behavior.is_top = 1;
          } else {
            feed.user_behavior.is_top = 0;
          }
          this.setData({
            feed
          });
        } else {
          wx.showModal({
            title: '失败',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  commentAcitonSheet(e) {
    const { feed } = this.data;
    const { thread_id } = feed;
    this.setData({
      receiver: e.currentTarget.dataset.comment
    })
    let itemList = this.commentAcitonSheetList();
    wx.showActionSheet({
      itemList,
      success: (res) => {
        const index = res.tapIndex;
        console.log(typeof index);
        if (typeof index == 'number') {
          switch (itemList[index]) {
            case '删除': {
              this.commentDelete();
              break;
            }
            case '点赞': ;
            case '取消点赞': {
              this.commentLike();
              break;
            }
            case '回复': {
              try {
                wx.setStorageSync('feed', feed);
                wx.setStorageSync('receiver', this.data.receiver);
              } catch (e) {
                console.log(e);
              }
              wx.navigateTo({ url: '/pages/comment/index' });
              break;
            }
            default: ;
          }
        }
        console.log(res)
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  commentAcitonSheetList() {
    const {receiver, user} = this.data;
    let menus = [];
    console.log(receiver.author_id);
    console.log(user.user_id);
    if (receiver.author_id == user.user_id) {
      if (receiver.praise_mine) {
        menus = ['删除', '取消点赞'];
      } else {
        menus = ['删除', '点赞'];
      }
    } else if (receiver.praise_mine) {
      menus = ['回复', '取消点赞'];
    } else {
      menus = ['回复', '点赞'];
    }
    return menus;
  },
  commentLike() {
    const {receiver, commentList} = this.data;
    wx.request({
      url: apiUrl + '/comment-like', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        comment_id: receiver.comment_id
      },
      header: {
        Authorization: token
      },
      success: (res) => {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          setTimeout(function () {
            wx.hideToast()
          }, 2000);
          const index = indexOf(commentList, find(commentList, { comment_id: receiver.comment_id }));
          if (index !== -1) {
            if (commentList[index].praise_mine) {
              commentList[index].praise_count--;
            } else {
              commentList[index].praise_count++;
            }
            commentList[index].praise_mine = !!!commentList[index].praise_mine;
          }
          this.setData({
            commentList
          });
        } else {
          wx.showModal({
            title: '失败',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  commentDelete() {
    const {receiver, commentList, feed} = this.data;
    wx.request({
      url: apiUrl + '/post-comment/' + receiver.comment_id, //仅为示例，并非真实的接口地址
      method: 'DELETE',
      header: {
        Authorization: token
      },
      success: (res) => {
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          setTimeout(function () {
            wx.hideToast()
          }, 2000);
          const index = indexOf(commentList, find(commentList, { comment_id: receiver.comment_id }));
          commentList.splice(index, 1);
          feed.replies--;
          this.setData({
            commentList,
            feed
          });
        } else {
          wx.showModal({
            title: '失败',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  switchType(e) {
    let metaType;
    if (typeof e == 'string') {
      metaType = e;
    } else {
      metaType = e.currentTarget.dataset.type;
    }
    this.setData({
      metaType,
      hasMore: true,
      getting: false,
      getSuccess: true,
      nextPage: 1,
    })
    switch (metaType) {
      case 'comment': {
        this.setData({
          commentList: [],
        });
        this.getFeedComment();
        break;
      }
      case 'like': {
        this.setData({
          likeList: [],
        });
        this.getFeedLike();
        break;
      }
      default: ;
    }
    console.log(e);
  },
  loadMore() {
    const { metaType, hasMore } = this.data;
    if (!hasMore) {
      return;
    }
    switch (metaType) {
      case 'comment': {
        this.getFeedComment();
        break;
      }
      case 'like': {
        this.getFeedLike();
        break;
      }
      default: ;
    }
  },
  getFeedComment() {
    const { nextPage, getting, commentMore, getSuccess, feed } = this.data;
    const { thread_id } = feed;
    wx.request({
      url: apiUrl + '/post-comment', //仅为示例，并非真实的接口地址
      data: {
        thread_id,
        page: nextPage
      },
      header: {
        Authorization: token
      },
      success: (res) => {
        console.log(res);
        switch (Number(res.data.code)) {
          case 1: {
            const filterUid = this.data.filterUid;
            let comments = [];
            if (!!filterUid) {
              comments = res.data.data.data.filter(comment => {
                if (!!filterUid) {
                  if (comment.author_id == filterUid) {
                    return comment;
                  }
                } else {
                  return comment;
                }
              });
            } else {
              comments = res.data.data.data;
            }
            this.setData({
              commentList: this.data.commentList.concat(comments),
              nextPage: nextPage + 1,
              hasMore: res.data.data.data.length >= res.data.data.per_page,
              getSuccess: true,
              getting: false
            });
            break;
          }
          default: {
            this.setData({
              commentList: [],
              getSuccess: false,
              getting: false,
              hasMore: true
            });
            break;
          }
        }
      },
      fail: () => {
        this.setData({
          commentList: [],
          getSuccess: false,
          getting: false
        });
      }
    })
  },
  getFeedLike() {
    const { nextPage, getting, likeMore, getSuccess, feed } = this.data;
    const { thread_id } = feed;
    wx.request({
      url: apiUrl + '/post-like', //仅为示例，并非真实的接口地址
      data: {
        type: 1,
        thread_id,
        page: nextPage
      },
      header: {
        Authorization: token
      },
      success: (res) => {
        console.log(res);
        switch (Number(res.data.code)) {
          case 1: {
            console.log(res.data.data.data);
            const afterLikes = res.data.data.data.map(item => {
              item.fromNow = fromNow(item.dateline);
              console.log(item);
              return item;
            });
            this.setData({
              likeList: this.data.likeList.concat(afterLikes),
              nextPage: nextPage + 1,
              hasMore: res.data.data.data.length >= res.data.data.per_page,
              getSuccess: true,
              getting: false
            });
            break;
          }
          default: {
            this.setData({
              likeList: [],
              getSuccess: false,
              getting: false
            });
            break;
          }
        }
      },
      fail: () => {
        this.setData({
          likeList: [],
          getSuccess: false,
          getting: false
        });
      }
    })
  },
  goComment() {
    const {feed} = this.data;
    try {
      wx.setStorageSync('feed', feed);
    } catch (e) {
      console.log(e);
    }
    wx.navigateTo({
      url: `/pages/comment/index?thread_id=${feed.thread_id}&index=${-1}`
    })
  },
  postLike() {
    const {feed} = this.data;
    const thread_id = feed.thread_id;
    wx.request({
      url: apiUrl + '/post-like', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        thread_id
      },
      header: {
        Authorization: token
      },
      success: (res) => {
        console.log(res);
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'success'
          });
          setTimeout(function () {
            wx.hideToast()
          }, 2000);
          const isLike = feed.user_behavior.is_like;
          feed.user_behavior.is_like = !isLike;
          if (isLike) {
            feed.total.likes--
            console.log('--');
          } else {
            feed.total.likes++
          }
          this.switchType('like');
          this.setData({
            feed
          });
        } else {
          wx.showModal({
            title: '失败',
            showCancel: false,
            content: res.data.msg
          })
        }
      },
      fail: (err) => {
        console.log(err)
      }
    })
  }
});
